<template>
  <div>
    <div style="position: relative; overflow-y: auto;overflow-x: hidden;padding-bottom: 15px;">
<!--      <div class="confirm-order-more-shop-item-shadebox" :style="{-->
<!--        left: ((this.getWinSize().width*0.02).toFixed(2))+'px'-->
<!--      }"></div>-->
      <div class="shop-and-product-box">
        <div class="shop-info">
          <div class="shop-logo">
            <img :src="shop.logo"/>
          </div>
          <div class="shop-name" v-text="shop.name"></div>
        </div>
        <product-list-item :ref="'product-list-item-'+index" v-for="(product,index) in productList" :key="index" :show-type="1" :curr-product="{
          id:product.shopProductId,
          name:product.shopProductName,
          model:product.model,
          nums:product.nums,
          price:product.price,
          score:product.score,
          image:product.image?product.image:product.shopProductImage,
        }"
                           :only-read="($route.query.shopSkillId && $route.query.shopSkillId>0)?1:0"
                           :choose-model-call-back="chooseModel"
                           :curr-index="index"
                           :change-call-back="function(nums) {
                             changeNums(index,nums)
                           }"/>
        <div class="choose-send" style="border-bottom: 1px solid #f1f1f1">
          <div class="left">商品金额:</div>
          <div class="right"><span class="red b" v-text="ToMoney(productPrice)"></span></div>
        </div>
        <div class="choose-send" style="border-bottom: 1px solid #f1f1f1; position: relative">
          <div class="left">配送方式</div>
          <div class="right">
            <div class="send-type" @click="chooseSendType">
              <span v-text="dict.OrderSendTypeArr[sendType]"></span>
              <i class="el-icon-arrow-right"></i>
            </div>
            <div class="same-city-send-error-info" v-if="sameCityErrorInfo && sameCityErrorInfo.length>0">
              {{ sameCityErrorInfo }}
            </div>
            <div class="send-time" @click="chooseSendTime" v-if="sendType===1 && currMemberAddress.id>0 && !sameCityErrorInfo">
              <div class="same-city-send-info"
                   v-html="sameCitySendInfo?sameCitySendInfo+' 前送达':'<span>请选择配送时间</span>'"></div>
            </div>
            <div class="send-data" v-if="sendType===1 && currMemberAddress.id>0 && sendData.sendPrice>0 && !sameCityErrorInfo">
              <div class="send-data-info">
                <!--                <span>
                                  时长: {{ sendData.time + '分钟' }}
                                </span>-->
                <span>
                  距离: {{ (sendData.sendDistance * 0.001).toFixed(2) + 'km' }}
                </span>
                <span>
                  费用: {{ ToMoney(sendData.sendPrice) }}
                </span>
              </div>
            </div>
          </div>
        </div>
        <div class="choose-send" v-if="sendType===0" style="border-bottom: 1px solid #f1f1f1">
          <div class="left">配送费用:
            <div class="tip-box coupon-use-box" v-if="expressPrice===0">免配送费</div>
          </div>
          <div class="right">
            <span class="b" v-if="expressPrice===0">-</span>
            <!--Vip免配送费-->
            <el-tag v-if="isOrderFreeSendPrice" type="success">Vip免配送费</el-tag>
            <!--店铺免配送费-->
            <div class="tip-box free-express-price" v-if="!isOrderFreeSendPrice && expressPrice===0">
              免配送费
            </div>
          </div>
        </div>
        <div class="choose-send" style="border-bottom: 1px solid #f1f1f1">
          <div class="left">优惠券:
            <span span class="tip-box coupon-use-box" v-if="useAbleCouponList.length>0" @click="chooseCoupon"> {{ useAbleCouponList.length }}张 可用优惠券</span>
          </div>
          <div class="right">
            <span v-if="currCoupon && currCoupon.reduceMoney" class="red b" v-text="'-'+ToMoney(currCoupon.reduceMoney)"></span>
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
        <div class="choose-send" style="border-bottom: 1px solid #f1f1f1" v-if="currFullMinus && currFullMinus.minus>0">
          <div class="left">店铺满减:
            <span class="tip-box coupon-use-box"  v-if="currFullMinus && currFullMinus.minus>0" > {{ '满'+currFullMinus.full+',减'+currFullMinus.minus }} </span>
          </div>
          <div class="right">
            <span v-if="currFullMinus && currFullMinus.minus>0" class="red b" v-text="'-'+ToMoney(currFullMinus.minus)"></span>
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
<!--        <div class="choose-send" v-if="currMember.isVip && currMember.vipDiscount<1" style="border-bottom: 1px solid #f1f1f1">
          <div class="left">Vip折扣:
            <el-tag type="success" > {{ dict.VipLevelMap[currMember.level] }} </el-tag>
            <el-tag type="warning" > {{ '折扣 '+(currMember.vipDiscount*100).toFixed(0)+'%' }} </el-tag>
          </div>
          <div class="right">
            <span class="red b" v-text="'-'+ToMoney(vipDiscountPrice)"></span>
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>-->
        <div class="choose-send">
          <div class="left">是否带发票</div>
          <div class="right">
            <!--            <el-switch-->
            <!--              v-model="isInvoice"-->
            <!--              active-color="#13ce66"-->
            <!--              inactive-color="#CCCCCC">-->
            <!--            </el-switch>-->
            <div class="send-type" @click="chooseInvoiceInfo">
              <span v-text="invoiceInfo.name?invoiceInfo.name+'('+invoiceInfo.typeName+')':'-'"></span>
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </div>
        <div class="choose-send">
          <div class="left">附言</div>
          <div class="right">
            <el-input type="textarea" v-model="info" maxlength="100" placeholder="订单备注"></el-input>
          </div>
        </div>
        <div class="c"></div>
      </div>
    </div>

    <level-info-dialog ref="level-info-dialog"/>
  </div>
</template>

<script>
import AddressItem from './AddressItem'
import ProductListItem from './ProductListItem'
import CartTools from '../tools/CartTools'
import LevelInfoDialog from './LevelInfoDialog'

export default {
  name: 'ConfirmOrderMoreShopItem',
  components: {LevelInfoDialog, ProductListItem, AddressItem},
  props:{
    selectData:Object,
    currMemberAddress:Object,
    currMember:Object,
    levelMap:Object,
    getCouponList:Function,
    setCoupon:Function,
    checkNeedAddress:Function,
    callBackCalcProductMoney:Function,
    callback:Function,
  },
  data: function () {
    return {
      isInvoice: true,
      invoiceInfo: {
        name: '',
        number: '',
        bankAccount: '',
        addressMobile: ''
      },
      info: '',
      sendType: 0,
      sameCitySendInfo: '',
      isGet: true,
      totalMoney: 0,
      accountMoney: -1,
      accountScore: -1,
      accountLevel: -1,
      productScore: -1,
      vipDiscount: 0,
      vipDiscountPrice: 0,
      isOrderFreeSendPrice: false,
      sameCityErrorInfo:'',
      shop: {},
      productList: [],
      productNums: 0,
      couponList: [],
      useAbleCouponList: [],
      productBuyNumsMap: {},
      productPrice: 0,
      expressPrice: 10,
      currCoupon: {},
      currFullMinus: {
        full: 0,
        minus: 0,
      },
      shopDiscountPrice: -15,
      price: 180,
      sendData: {
        sendPrice: 0,
        time: '',
        sendDistance: 0
      }
    }
  },
  watch:{
    sendType:function () {
        this.checkSameCitySend()
        this.$props.checkNeedAddress()
    }
  },
  mounted () {
    let $this = this
    $this.initData(function () {

    })
  },
  methods: {
    chooseModel: function (item,index) {
      let $this = this
      if ($this.$route.query.type && $this.$route.query.type !== 'one') {
        return
      }
      $this.MyRequest($this.ApiDoNameMember + 'ShopProduct/getDetail', {
        id: item.id,
        model: item.model,
      }, function (productDetail) {
        $this.bus.$emit('ProductChooseModelDialogCallBus', 'productDetail', productDetail, function (stock) {
          var currProduct=$this.productList[index]
          $this.$set($this.productList[index],'model',stock.model)
          $this.$set($this.productList[index],'price',stock.price)
          $this.$set($this.productList[index],'image',stock.image)
          $this.$set($this.productList[index],'id',stock.id)
          $this.$set($this.productList[index],'score',!stock.score?0:stock.score)
          $this.calcProductMoney()
          $this.quChongProductList()
        })
        $this.$forceUpdate()
      })
    },
    // 选择发票信息
    chooseInvoiceInfo: function () {
      let $this = this
      $this.bus.$emit('ChooseInvoiceInfoDialogCallBus', $this.invoiceInfo, function (invoiceInfo) {
        $this.invoiceInfo = invoiceInfo
        $this.$forceUpdate()
      })
    },
    // 初始化信息
    initData: function (callback) {
      this.shop = this.$props.selectData.shop
      this.productList = this.$props.selectData.productList
      this.calcProductMoney()
      this.couponList=this.$props.getCouponList()
      callback()
    },
    calcProductMoney: function () {
      var productPrice = 0
      var productScore = 0
      let $this = this
      this.productNums=0
      this.productList.forEach(function (product, index) {
        productScore=(productScore + ((product.nums * product.score).toFixed(2) - 0)).toFixed(2) - 0
        productPrice = (productPrice + ((product.nums * product.price).toFixed(2) - 0)).toFixed(2) - 0
        $this.productNums+=product.nums
      })
      $this.price = productPrice
      $this.productPrice = productPrice
      $this.productScore = productScore

      // ========= 运费计算 =========
      if (this.productPrice >= this.shop.freeExpressPrice) {
        this.expressPrice = 0
      }else{
        this.expressPrice = this.shop.expressPrice
      }
      if ($this.sendType === 1 && $this.sendData.sendPrice > 0) {
        $this.expressPrice = $this.sendData.sendPrice
      }
      // 会员-免运费

      if ($this.currMember.level > 0 && this.sendType === 0) {
        if ($this.levelMap[$this.currMember.level].isOrderFreeSendPrice === 1) {
          $this.expressPrice = 0
          $this.isOrderFreeSendPrice = true
          $this.price = ($this.price - $this.expressPrice).toFixed(2) - 0
        } else {
          $this.isOrderFreeSendPrice = false
        }
      }

      var currFull = {
        full: 0,
        minus: 0,
      }
      this.shop.fullMinusPrice.forEach(function (item, index) {
        if (item.full <= $this.productPrice && item.minus > currFull.minus) {
          currFull = item
        }
      })
      $this.currFullMinus = currFull
      if ($this.sendType === 2) {
        $this.expressPrice = 0
      }
      if ($this.currFullMinus.minus > 0) {
        $this.price = (productPrice - $this.currFullMinus.minus).toFixed(2) - 0
      }
      if ($this.expressPrice > 0) {
        $this.price = ($this.price + $this.expressPrice).toFixed(2) - 0
      }
      if ($this.currCoupon.id > 0) {
        if ($this.productPrice<$this.currCoupon.fullMoney){
          // 优惠券，满足条件失效
          $this.$props.setCoupon($this.currCoupon.id,$this.shop.id)
          $this.currCoupon={
            id:0,
            fullMoney:0,
            reduceMoney:0,
          }
        }else{
          $this.price = ($this.price - $this.currCoupon.reduceMoney).toFixed(2) - 0
        }
      }

      // console.log('$this.productPrice', $this.productPrice)
      // console.log('$this.couponList', $this.couponList)
      // 筛选优惠券
      // console.log('筛选优惠券')
      var tmpList = []
      $this.couponList=$this.$props.getCouponList()
      // console.log('$this.couponList ====',$this.couponList)
      $this.couponList.forEach(function (value, index) {
        if (value.fullMoney <= $this.productPrice) {
          tmpList.push(value)
        }
      })
      $this.useAbleCouponList = tmpList
      // console.log('$this.useAbleCouponList',$this.useAbleCouponList)

      // 积分兑换
      // if (this.$route.query && this.$route.query.extendType === 'score') {
      //   this.productScore = this.productList[0].nums * this.$route.query.score
      // }

      // 会员优惠金额
      this.vipDiscountPrice=0
      if (this.currMember.vipDiscount>0){
        this.vipDiscountPrice = ((1 - this.currMember.vipDiscount) * $this.productPrice).toFixed(2) - 0
      }
      this.price = (this.price - this.vipDiscountPrice).toFixed(2) - 0
      this.getCoupon()
      this.$props.callBackCalcProductMoney()
      this.$forceUpdate()
    },
    // 商品列表去重
    quChongProductList: function () {
      let numsMap={}
      let $this=this
      $this.productList.forEach(function (productStock, index) {
        var key=productStock.id
        if (!numsMap[key]){
          numsMap[key]=0
        }
        numsMap[key]+=productStock.nums
      })

      var productIdModelArr=[]
      var newProductList=[]
      $this.productList.forEach(function (productStock, index) {
        var key=productStock.id
        if (productIdModelArr.indexOf(key)===-1){
          productIdModelArr.push(key)
          productStock.nums=numsMap[key]
          newProductList.push(productStock)
        }
      })

      $this.productList=newProductList
      $this.$forceUpdate()
    },
    // 更改数量回调
    changeNums: function (index,nums) {
      let $this=this
      $this.$set($this.productList[index],'nums',nums)
      this.calcProductMoney()
    },
    // 获取可用优惠券
    getCoupon:function () {
      let $this=this
      var classifyIdArr=[]
      $this.selectData.productList.forEach(function (value, index) {
        if (classifyIdArr.indexOf(value.classifyId)===-1){
          classifyIdArr.push(value.classifyId)
        }
      })
      $this.useAbleCouponList=$this.$props.getCouponList(this.$props.selectData.shop.id,classifyIdArr,this.productPrice)
      $this.$forceUpdate()
    },
    chooseCoupon: function () {
      let $this = this
      if (!this.useAbleCouponList || this.useAbleCouponList.length === 0) {
        return
      }
      $this.bus.$emit('ChooseCouponDialogCallBus', this.productPrice, this.useAbleCouponList, function (coupon) {
        // 设置之间失效
        if ($this.currCoupon && $this.currCoupon.id>0){
          $this.$props.setCoupon($this.currCoupon.id,$this.$props.selectData.shop.id,0)
        }
        $this.currCoupon = coupon
        // 标记当前使用
        $this.$props.setCoupon(coupon.id,$this.$props.selectData.shop.id,1)
        $this.calcProductMoney()
      },$this.currCoupon)
    },
    chooseSendType: function () {
      let $this = this
      $this.bus.$emit('ChooseSendTypeDialogCallBus', this.sendType, function (sendType) {
        $this.sendType = sendType
        if (sendType === 1) {
          $this.checkSameCitySend()
        } else {
          $this.sendData = {
            sendPrice: 0,
            sendDistance: 0,
            time: '',
          }
          $this.calcProductMoney()
        }
        $this.$forceUpdate()
      })
    },
    checkSameCitySend: function () {
      let $this = this
      if ($this.sendType!==1){
        $this.sendData = {
          sendPrice: 0,
          distance: 0,
          time: '',
        }
        $this.sameCityErrorInfo=''
        return;
      }
      // console.log('$this.addressId',$this.address.id)
      if (!$this.$props.currMemberAddress || !$this.$props.currMemberAddress) {
        return
      }
      $this.MyRequest($this.ApiDoNameMember + 'Order/getSendDataByAddress', {
        shopId: $this.shop.id,
        memberAddressId: $this.currMemberAddress.id
      }, function (sendData) {
        $this.sendData = sendData
        $this.calcProductMoney()
        $this.$forceUpdate()
      }, function (res) {
        $this.sendData = {
          sendPrice: 0,
          distance: 0,
          time: '',
        }
        $this.sameCityErrorInfo=res.message
        $this.$forceUpdate()
      })
    },
    chooseSendTime: function () {
      let $this = this
      if (!$this.currMemberAddress || !$this.currMemberAddress.id) {
        return $this.successTip('请先选择地址')
      }
      if ($this.sendType === 1 && $this.sendData.sendPrice === 0) {
        return $this.$message.warning('当前地址不在配送范围内')
      }
      $this.bus.$emit('ShopSendTimeDialogCallBus', this.shop.id, this.currMemberAddress.id, function (sameCitySendInfo) {
        $this.sameCitySendInfo = sameCitySendInfo
        $this.$forceUpdate()
      })
    },
    // 检查是否可以提交
    getSubmit:function () {
      let $this=this
      if ($this.sendType===1 && !$this.sameCitySendInfo){
        $this.$message.error('请选择 配送时间')
        return false
      }
      var tmpProductBuyNumsList=[]
      $this.productList.forEach(function (product, index) {
        tmpProductBuyNumsList.push({
          id:product.shopProductId,
          model:product.model,
          nums:product.nums
        })
      })


      return {
        shopId:this.shop.id,
        sendType:this.sendType,
        sendTime:this.sendType===1?this.sameCitySendInfo:'',
        extendType:this.extendType,
        productBuyNumsList:JSON.stringify(tmpProductBuyNumsList),
        addressId:this.$props.currMemberAddress.id,
        couponId:this.currCoupon.id,
        // isInvoice: $this.isInvoice ? 1 : 0,
        invoiceInfo:$this.invoiceInfo.name?this.invoiceInfo:'',
        info:this.info,
      }
    },
    // 获取金额
    getPrice:function () {
      return {
        productNums:this.productNums,
        productPrice:this.productPrice,
        couponPrice:this.currCoupon && this.currCoupon.id>0?this.currCoupon.reduceMoney:0,
        expressPrice:this.expressPrice?this.expressPrice:0,
        fullMinusPrice:this.currFullMinus.minus,
        vipDiscountPrice:this.vipDiscountPrice,
      }
    }
  }
}
</script>

<style scoped>

</style>
